<template>
	<div class="asset-risk-analysis">
		<!-- 左侧导航栏 -->
		<div class="left-nav-panel">
			<el-tabs v-model="activeTab" class="nav-tabs" stretch>
				<el-tab-pane label="存量" name="stock">
					<div class="nav-content">
						<div class="nav-item" :class="{ active: activeNavItem === 'value' }"
							@click="onNavItemClick('value')">
							<span class="nav-title">价值资产墙</span>
						</div>
						<div class="nav-item" :class="{ active: activeNavItem === 'physical' }"
							@click="onNavItemClick('physical')">
							<span class="nav-title">实物资产墙</span>
						</div>
						<div class="nav-item" :class="{ active: activeNavItem === 'pricing' }"
							@click="onNavItemClick('pricing')">
							<span class="nav-title">核价资产墙</span>
						</div>
					</div>
				</el-tab-pane>

				<el-tab-pane label="增量" name="increment">
					<div class="nav-content">
						<div class="nav-item active">
							<span class="nav-title">价值资产墙</span>
						</div>
						<div class="nav-item">
							<span class="nav-title">实物资产墙</span>
						</div>
						<div class="nav-item">
							<span class="nav-title">核价资产墙</span>
						</div>
					</div>
				</el-tab-pane>

				<el-tab-pane label=" 风险评估 " name="risk">
					<div class="nav-content">
						<div class="nav-item active">
							<span class="nav-title">价值资产墙</span>
						</div>
						<div class="nav-item">
							<span class="nav-title">实物资产墙</span>
						</div>
						<div class="nav-item">
							<span class="nav-title">核价资产墙</span>
						</div>
						<div class="nav-item">
							<span class="nav-title">综合对比</span>
						</div>
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>

		<!-- 主内容区域 -->
		<div class="main-content">
			<!-- 模型脚本区域 -->
			<div class="model-script-section">
				<div class="card-title">模型脚本</div>
				<div class="code-editor">
					<pre class="code-content">
set odps.sql.type.system.odps2=true;
CREATE OR REPLACE VIEW vw_assets_base AS
WITH raw AS (
  SELECT
      operate_date,
      EXTRACT(YEAR FROM operate_date)  AS 年份,
      city_name       AS 所属地市名称,
      ast_category_name       AS 资产大类名称,
      ast_middlecategory_name AS 资产中类名称,
      -- 电压等级名称
      CASE voltage_level
        WHEN '01' THEN '交流6V'
        WHEN '02' THEN '交流12V'
        WHEN '03' THEN '交流24V'
        WHEN '04' THEN '交流36V'
        WHEN '05' THEN '交流48V'
        WHEN '06' THEN '交流110V'
        WHEN '07' THEN '交流220V'
        WHEN '08' THEN '交流380V(含400V)'
        WHEN '09' THEN '交流660V'
        WHEN '10' THEN '交流1000V（含1140V）'
        WHEN '11' THEN '交流600V'
        WHEN '12' THEN '交流750V'
        WHEN '13' THEN '交流1500V'
        WHEN '14' THEN '交流3000V'
        WHEN '15' THEN '交流2500V'
        WHEN '20' THEN '交流3kV'
        WHEN '21' THEN '交流6kV'
        WHEN '22' THEN '交流10kV'
        WHEN '23' THEN '交流15kV'
        WHEN '24' THEN '交流20kV'
        WHEN '30' THEN '交流66kV'
        WHEN '31' THEN '交流110kV'
        WHEN '32' THEN '交流220kV'
        WHEN '33' THEN '交流330kV'
        WHEN '34' THEN '交流500kV'
        WHEN '35' THEN '交流750kV'
        WHEN '36' THEN '交流1000kV'
        WHEN '51' THEN '直流6V'
        WHEN '52' THEN '直流12V'
        WHEN '53' THEN '直流24V'
        WHEN '54' THEN '直流36V'
        WHEN '55' THEN '直流48V'
        WHEN '56' THEN '直流110V'
        WHEN '57' THEN '直流200kV'
        WHEN '60' THEN '直流220V'
        WHEN '65' THEN '直流320kV'
        WHEN '70' THEN '直流600V'
        WHEN '71' THEN '直流750V'
        WHEN '72' THEN '直流1500V'
        WHEN '73' THEN '直流3000V'
        WHEN '80' THEN '直流120kV'
        WHEN '81' THEN '直流125kV'
        WHEN '82' THEN '直流400kV'
        WHEN '83' THEN '直流500kV'
        WHEN '84' THEN '直流660kV'
        WHEN '85' THEN '直流800kV'
        WHEN '86' THEN '直流1000kV'
        WHEN '87' THEN '直流1100kV'
        ELSE ''
      END      AS 电压等级名称,
      ast_original_value  AS 资产原值
  FROM pro_dwd_pms_prd_1.un156_02_pms30_pa_asset_equip_collect_pl
  WHERE ds = max_pt('pro_dwd_pms_prd_1.un156_02_pms30_pa_asset_equip_collect_pl')
    AND EXTRACT(YEAR FROM operate_date) > 2003
    AND EXTRACT(YEAR FROM operate_date) < 2025
),
norm AS (
  SELECT
    年份,
    所属地市名称,
    资产大类名称,
    资产中类名称,
    CASE WHEN 电压等级名称 = '交流380V(含400V)' THEN '交流380V'
         ELSE 电压等级名称 END AS 电压等级,                    

    资产原值
  FROM raw
),


with_city AS (
  SELECT 年份,
    -- 地市归并
 (CASE 
      WHEN 所属地市名称 like '%泉州%' THEN '泉州'
      WHEN 所属地市名称 like '%漳州%' THEN '漳州'
      WHEN 所属地市名称 like '%宁德%' THEN '宁德'
      WHEN 所属地市名称 like '%福州%' THEN '福州'
      WHEN 所属地市名称 like '%福清%' THEN '福州'
      WHEN 所属地市名称 like '%南平%' THEN '南平'
      WHEN 所属地市名称 like '%三明%' THEN '三明'
      WHEN 所属地市名称 like '%龙岩%' THEN '龙岩'
      WHEN 所属地市名称 like '%莆田%' THEN '莆田'
      WHEN 所属地市名称 like '%厦门%' THEN '厦门'
      WHEN 所属地市名称 like '%超高压%' THEN '其他'
      ELSE ''
    END )AS 地市,
    资产大类名称,
    资产中类名称,
    电压等级,
    资产原值
  FROM norm
)
SELECT * FROM with_city;




--参数“会计年度”“地市”“资产大类”不同选择下的计算方式
--（1）年×三大类（变电设备、输电线路、配电线路及设备）


SELECT
  年份,
  ROUND(SUM(CASE WHEN 资产大类名称 = '变电设备'       THEN 资产原值 END)/1e8, 6) AS 变电设备,
  ROUND(SUM(CASE WHEN 资产大类名称 = '输电线路'       THEN 资产原值 END)/1e8, 6) AS 输电线路,
  ROUND(SUM(CASE WHEN 资产大类名称 = '配电线路及设备' THEN 资产原值 END)/1e8, 6) AS 配电线路及设备
FROM vw_assets_base
WHERE 资产大类名称 IN ('变电设备','输电线路','配电线路及设备')
GROUP BY 年份
ORDER BY 年份;

--（2）年×1
SELECT
  年份,
  ROUND(SUM(CASE WHEN 地市 = '福州' THEN 资产原值 END)/1e8, 6) AS 福州,
  ROUND(SUM(CASE WHEN 地市 = '莆田' THEN 资产原值 END)/1e8, 6) AS 莆田,
  ROUND(SUM(CASE WHEN 地市 = '泉州' THEN 资产原值 END)/1e8, 6) AS 泉州,
  ROUND(SUM(CASE WHEN 地市 = '厦门' THEN 资产原值 END)/1e8, 6) AS 厦门,
  ROUND(SUM(CASE WHEN 地市 = '漳州' THEN 资产原值 END)/1e8, 6) AS 漳州,
  ROUND(SUM(CASE WHEN 地市 = '龙岩' THEN 资产原值 END)/1e8, 6) AS 龙岩,
  ROUND(SUM(CASE WHEN 地市 = '三明' THEN 资产原值 END)/1e8, 6) AS 三明,
  ROUND(SUM(CASE WHEN 地市 = '南平' THEN 资产原值 END)/1e8, 6) AS 南平,
  ROUND(SUM(CASE WHEN 地市 = '宁德' THEN 资产原值 END)/1e8, 6) AS 宁德,
  ROUND(SUM(CASE WHEN 地市 = '其他' THEN 资产原值 END)/1e8, 6) AS 其他
FROM vw_assets_base
WHERE 地市 <> ''
GROUP BY 年份
ORDER BY 年份;

--（3）年×电压等级（仅“变电设备”）
SELECT
  年份,
  ROUND(SUM(CASE WHEN 电压等级='交流110V' THEN 资产原值 END)/1e8, 6)  AS 交流110V,
  ROUND(SUM(CASE WHEN 电压等级='交流220V' THEN 资产原值 END)/1e8, 6)  AS 交流220V,
  ROUND(SUM(CASE WHEN 电压等级='交流380V' THEN 资产原值 END)/1e8, 6)  AS 交流380V,
  ROUND(SUM(CASE WHEN 电压等级='交流3kV'  THEN 资产原值 END)/1e8, 6)  AS 交流3kV,
  ROUND(SUM(CASE WHEN 电压等级='交流6kV'  THEN 资产原值 END)/1e8, 6)  AS 交流6kV,
  ROUND(SUM(CASE WHEN 电压等级='交流10kV' THEN 资产原值 END)/1e8, 6)  AS 交流10kV,
  ROUND(SUM(CASE WHEN 电压等级='交流15kV' THEN 资产原值 END)/1e8, 6)  AS 交流15kV,
  ROUND(SUM(CASE WHEN 电压等级='交流20kV' THEN 资产原值 END)/1e8, 6)  AS 交流20kV,
  ROUND(SUM(CASE WHEN 电压等级='交流66kV' THEN 资产原值 END)/1e8, 6)  AS 交流66kV,
  ROUND(SUM(CASE WHEN 电压等级='交流110kV' THEN 资产原值 END)/1e8, 6) AS 交流110kV,
  ROUND(SUM(CASE WHEN 电压等级='交流220kV' THEN 资产原值 END)/1e8, 6) AS 交流220kV,
  ROUND(SUM(CASE WHEN 电压等级='交流330kV' THEN 资产原值 END)/1e8, 6) AS 交流330kV,
  ROUND(SUM(CASE WHEN 电压等级='交流500kV' THEN 资产原值 END)/1e8, 6) AS 交流500kV,
  ROUND(SUM(CASE WHEN 电压等级='交流750kV' THEN 资产原值 END)/1e8, 6) AS 交流750kV
FROM vw_assets_base
WHERE 资产大类名称 = '变电设备'
  AND COALESCE(电压等级,'') <> ''
GROUP BY 年份
ORDER BY 年份;


--（4) 年×电压等级（仅“配电线路及设备”）
SELECT
  年份,
  ROUND(SUM(CASE WHEN 电压等级='交流380V' THEN 资产原值 END)/1e8, 6) AS 交流380V,
  ROUND(SUM(CASE WHEN 电压等级='交流6kV'  THEN 资产原值 END)/1e8, 6) AS 交流6kV,
  ROUND(SUM(CASE WHEN 电压等级='交流10kV' THEN 资产原值 END)/1e8, 6) AS 交流10kV
FROM vw_assets_base
WHERE 资产大类名称 = '配电线路及设备'
  AND COALESCE(电压等级,'') <> ''
GROUP BY 年份
ORDER BY 年份;


--（5) 年×电压等级（仅“输电线路”）
SELECT
  年份,
  ROUND(SUM(CASE WHEN 电压等级='交流220kV' THEN 资产原值 END)/1e8, 6) AS 交流220kV,
  ROUND(SUM(CASE WHEN 电压等级='交流330kV' THEN 资产原值 END)/1e8, 6) AS 交流330kV,
  ROUND(SUM(CASE WHEN 电压等级='交流750kV' THEN 资产原值 END)/1e8, 6) AS 交流750kV
FROM vw_assets_base
WHERE 资产大类名称 = '输电线路'
  AND COALESCE(电压等级,'') <> ''
GROUP BY 年份
ORDER BY 年份;
					</pre>
				</div>
			</div>

			<!-- 参数配置区域 -->
			<div class="parameter-section">
				<div class="card-title">参数配置</div>
				<div class="parameter-form">
					<!-- 选择模式 -->
					<div class="selection-mode">
						<label class="mode-label">选择模式：</label>
						<label class="radio-item">
							<input type="radio" name="selectionMode" value="city" v-model="selectionMode">
							<span class="radio-text">按地市</span>
						</label>
						<label class="radio-item">
							<input type="radio" name="selectionMode" value="category" v-model="selectionMode">
							<span class="radio-text">按资产大类</span>
						</label>
					</div>

					<div class="form-row">
						<div class="form-item">
							<label>会计年度</label>
							<div class="year-range">
								<select v-model="startYear">
									<option v-for="year in yearOptions" :key="year" :value="year">{{ year }}</option>
								</select>
								<span class="separator">至</span>
								<select v-model="endYear">
									<option v-for="year in endYearOptions" :key="year" :value="year">{{ year }}</option>
								</select>
							</div>
						</div>
						<div class="form-item" v-show="false">
							<label>地市</label>
							<select v-model="city">
								<option value="fuZhou" selected>福州市</option>
								<option value="puTian">莆田市</option>
								<option value="quanZhou">泉州市</option>
								<option value="xiaMen">厦门市</option>
								<option value="zhangZhou">漳州市</option>
								<option value="longYan">龙岩市</option>
								<option value="sanMing">三明市</option>
								<option value="nanPing">南平市</option>
								<option value="ningDe">宁德市</option>
								<option value="qiTa">其他</option>
							</select>
						</div>
						<div class="form-item" v-show="selectionMode === 'category'">
							<label>资产大类</label>
							<select v-model="assetCategory">
								<option value="0">全部</option>
								<option value="1">变电设备</option>
								<option value="2">配电线路及设备</option>
								<option value="3">输电线路</option>
							</select>
						</div>
					</div>
					<div class="form-actions">
						<button class="btn btn-reset" @click="resetForm">重置</button>
						<button class="btn btn-execute" @click="executeAnalysis">执行</button>
					</div>
				</div>
			</div>

			<!-- 执行结果区域 -->
			<div class="result-section">
				<div class="card-title">执行结果</div>
				<el-tabs v-model="activeResultTab" class="result-tabs">
					<el-tab-pane label="表格" name="table">
						<div class="result-table">
							<table v-if="tableData.length > 0">
								<thead>
									<tr>
										<th>年度</th>
										<!-- 动态列头 -->
										<th v-for="column in dynamicColumns" :key="column.key">{{ column.label }}</th>
									</tr>
								</thead>
								<tbody>
									<tr v-for="(item, index) in tableData" :key="index">
										<td>{{ item.year }}</td>
										<!-- 动态列数据 -->
										<td v-for="column in dynamicColumns" :key="column.key">
											{{ formatVoltageValue(item[column.key]) }}
										</td>
									</tr>
								</tbody>
							</table>
							<div v-else class="no-data">
								<p>暂无数据，请选择参数后点击执行</p>
							</div>
						</div>
					</el-tab-pane>

					<el-tab-pane label="面积图" name="chart">
						<div class="chart-container">
							<div v-if="!chartData.length" class="chart-placeholder">
								<p>暂无数据，请先执行分析</p>
							</div>
							<div v-else id="areaChart" class="chart-content"></div>
						</div>
					</el-tab-pane>

					<el-tab-pane label="地图" name="map" v-if="selectionMode == 'city'">
						<div class="map-container">
							<div v-if="!mapData.length" class="map-placeholder">
								<p>暂无数据，请先执行分析</p>
							</div>
							<div v-else id="fujianMap" class="map-content"></div>
						</div>
					</el-tab-pane>
				</el-tabs>

				<div class="result-actions">
					<!-- <button class="btn btn-add-dataset">加入数据集</button> -->
					<button class="btn btn-export" @click="exportResults">导出结果表</button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { stockPhysicalData, dataAnalysisExport, stockPhysicalCityData, dataAnalysisExportCity } from '@/api/dataCenter'
import * as echarts from 'echarts'
import fujianMapData from '@/assets/map/350000.json'
import { areaData } from './data'
export default {
	name: 'AssetRiskAnalysis',
	data() {
		return {
			activeTab: 'stock',
			activeNavItem: 'value',
			startYear: '2024',
			endYear: '2024',
			selectionMode: 'city',
			city: 'fuZhou',
			assetCategory: '1',
			activeResultTab: 'table',
			tableData: [],
			mapData: [],
			chartData: [],
			loading: false,
			// 年份选项：从2003年到2025年
			yearOptions: Array.from({ length: 23 }, (_, i) => 2003 + i),
			// 不同资产大类对应的列配置
			columnConfigs: [
				[
					{ key: 'bdsb', label: '变电设备' },
					{ key: 'sdxl', label: '输电线路' },
					{ key: 'pdxljsb', label: '配电线路及设备' },

				],
				[
					{ key: 'ac110V', label: '交流110V' },
					{ key: 'ac220V', label: '交流220V' },
					{ key: 'ac380V', label: '交流380V' },
					{ key: 'ac3kV', label: '交流3kV' },
					{ key: 'ac6kV', label: '交流6kV' },
					{ key: 'ac10kV', label: '交流10kV' },
					{ key: 'ac15kV', label: '交流15kV' },
					{ key: 'ac20kV', label: '交流20kV' },
					{ key: 'ac66kV', label: '交流66kV' },
					{ key: 'ac110kV', label: '交流110kV' },
					{ key: 'ac220kV', label: '交流220kV' },
					{ key: 'ac330kV', label: '交流330kV' },
					{ key: 'ac500kV', label: '交流500kV' },
					{ key: 'ac750kV', label: '交流750kV' }
				],
				[
					{ key: 'ac380V', label: '交流380V' },
					{ key: 'ac6kV', label: '交流6kV' },
					{ key: 'ac10kV', label: '交流10kV' }
				],
				[
					{ key: 'ac220kV', label: '交流220kV' },
					{ key: 'ac330kV', label: '交流330kV' },
					{ key: 'ac750kV', label: '交流750kV' }
				]
			],
			// 地市列配置
			cityColumns: [
				{ key: 'fuZhou', label: '福州市', color: '#5470c6' },
				{ key: 'puTian', label: '莆田市', color: '#91cc75' },
				{ key: 'quanZhou', label: '泉州市', color: '#fac858' },
				{ key: 'xiaMen', label: '厦门市', color: '#ee6666' },
				{ key: 'zhangZhou', label: '漳州市', color: '#73c0de' },
				{ key: 'longYan', label: '龙岩市', color: '#3ba272' },
				{ key: 'sanMing', label: '三明市', color: '#fc8452' },
				{ key: 'nanPing', label: '南平市', color: '#9a60b4' },
				{ key: 'ningDe', label: '宁德市', color: '#ea7ccc' },
				{ key: 'qiTa', label: '其他', color: '#ff9f7f' }
			],
			dynamicColumns: []
		}
	},
	computed: {

		// 结束年份选项：显示大于等于开始年份的年份
		endYearOptions() {
			return this.yearOptions.filter(year => year >= this.startYear)
		}
	},
	watch: {
		// 监听结果标签页切换
		activeResultTab(newTab) {
			// 如果当前是按地市模式且有数据，切换标签页时重新获取数据
			if (this.selectionMode === 'city' && this.tableData.length > 0 && (newTab === 'table' || newTab === 'map')) {
				this.loadPhysicalData()
			} else if (newTab === 'chart') {
				// 切换到面积图时，如果有数据则渲染图表
				if (this.chartData.length > 0) {
					this.$nextTick(() => {
						this.renderAreaChart()
					})
				} else if (this.selectionMode === 'city' && this.tableData.length > 0) {
					// 如果是按地市模式且有表格数据，但没有图表数据，则重新获取数据
					this.loadPhysicalData()
				} else if (this.selectionMode === 'category') {
					// 如果是按资产大类模式且没有图表数据，则获取数据
					this.getChartData()
				}
			} else {
				// 直接渲染对应的地图
				if (newTab === 'map' && this.mapData.length > 0) {
					this.$nextTick(() => {
						this.renderFujianMap()
					})
				}
			}
		},
		// 监听选择模式变化
		selectionMode(newMode) {
			// 当选择模式改变时，清空数据并重置地图
			this.tableData = []
			this.mapData = []
			this.chartData = []

			// 清理地图实例
			if (this.$map) {
				this.$map.dispose()
				this.$map = null
			}

			// 清理图表实例
			if (this.$areaChart) {
				this.$areaChart.dispose()
				this.$areaChart = null
			}
		},
		// 监听开始年份变化
		startYear(newYear) {
			// 如果结束年份小于开始年份，重置结束年份
			if (this.endYear && this.endYear < newYear) {
				this.endYear = newYear
			}
		}
	},
	methods: {
		// 导航项点击事件
		onNavItemClick(navItem) {
			this.activeNavItem = navItem
			if (navItem === 'physical') {
				// 点击实物资产墙时，自动选择第一个资产大类
				if (!this.assetCategory) {
					this.assetCategory = '变电设备'
				}
			}
		},

		// 获取城市名称
		getCityName(cityCode) {
			const cityMap = {
				'fuZhou': '国网福州供电公司',
				'puTian': '国网莆田供电公司',
				'quanZhou': '国网泉州供电公司',
				'xiaMen': '国网厦门供电公司',
				'zhangZhou': '国网漳州供电公司',
				'longYan': '国网龙岩供电公司',
				'sanMing': '国网三明供电公司',
				'nanPing': '国网南平供电公司',
				'ningDe': '国网宁德供电公司',
				'qiTa': '其他'
			}
			return cityMap[cityCode] || cityCode
		},



		// 格式化数据值
		formatVoltageValue(value) {
			if (value === null || value === undefined) {
				return '-'
			}
			// 如果是按地市模式，直接返回数值
			if (this.selectionMode === 'city') {
				return value
			}
			// 如果是按资产大类模式，返回电压值
			return value
			// return value.toFixed(6)
		},

		// 重置表单
		resetForm() {
			this.startYear = '2024'
			this.endYear = '2024'
			this.selectionMode = 'city'
			this.city = 'fuZhou'
			this.assetCategory = '1'
			this.tableData = []
			this.mapData = []
			this.chartData = []

			// 清理图表实例
			if (this.$areaChart) {
				this.$areaChart.dispose()
				this.$areaChart = null
			}
		},

		// 执行分析
		async executeAnalysis() {
			// 验证参数
			if (this.selectionMode === 'city' && !this.city) {
				this.$message.warning('请选择地市')
				return
			}

			if (this.selectionMode === 'category' && !this.assetCategory) {
				this.$message.warning('请选择资产大类')
				return
			}

			if (this.activeNavItem === 'physical') {
				this.dynamicColumns = this.selectionMode === 'city' ? this.cityColumns : this.columnConfigs[Number(this.assetCategory)] || []
				await this.loadPhysicalData()
			} else {
				this.$message.info('该功能暂未实现')
			}
		},

		// 加载实物资产数据
		async loadPhysicalData() {
			this.loading = true
			try {
				const params = {
					// pageNum: 1,
					// pageSize: 10,
					yearStart: parseInt(this.startYear),
					yearEnd: parseInt(this.endYear)
				}

				// 根据选择模式添加相应参数
				if (this.selectionMode === 'city') {
					// 根据当前激活的结果标签页决定city参数值
					if (this.activeResultTab === 'table') {
						params.city = 1  // 1-列表
					} else if (this.activeResultTab === 'map') {
						params.city = 2  // 2-地图
					} else {
						params.city = 1  // 默认列表模式
					}
				} else if (this.selectionMode === 'category') {
					params.astCategory = this.assetCategory
				}

				// 按地市选择时调用stockPhysicalCityData接口
				let response
				if (this.selectionMode === 'city') {
					response = await stockPhysicalCityData(params)
				} else {
					response = await stockPhysicalData(params)
				}

				if (response.code == 200) {
					this.tableData = response.rows
					console.log(this.tableData)
					// 处理地图数据
					this.processMapData(response.rows)
					// 处理图表数据
					this.processChartData(response.rows)
					this.$message.success('数据加载成功')
				} else {
					this.$message.error(response.errMsg || '获取数据失败')
				}
			} catch (error) {
				console.error('加载实物资产数据失败:', error)
				this.$message.error('获取数据失败，请稍后重试')
			} finally {
				this.loading = false
			}
		},

		// 获取图表数据
		async getChartData() {
			try {
				const params = {
					yearStart: parseInt(this.startYear),
					yearEnd: parseInt(this.endYear)
				}

				// 按资产大类模式时，调用 stockPhysicalData 接口
				if (this.selectionMode === 'category') {
					params.astCategory = this.assetCategory
				}

				const response = await stockPhysicalData(params)
				if (response.code == 200) {
					this.chartData = response.rows
					// 如果当前在面积图标签页，立即渲染图表
					if (this.activeResultTab === 'chart' && this.chartData.length > 0) {
						this.$nextTick(() => {
							this.renderAreaChart()
						})
					}
				} else {
					this.$message.error(response.errMsg || '获取图表数据失败')
				}
			} catch (error) {
				console.error('获取图表数据失败:', error)
				this.$message.error('获取图表数据失败，请稍后重试')
			}
		},

		// 处理图表数据
		processChartData(data) {
			if (!data || data.length === 0) {
				this.chartData = []
				return
			}

			console.log('处理图表数据，选择模式:', this.selectionMode, '数据:', data)

			// 如果是按地市模式，直接使用传入的数据
			if (this.selectionMode === 'city') {
				this.chartData = data
				console.log('按地市模式，设置图表数据:', this.chartData)
				// 如果当前在面积图标签页，立即渲染图表
				if (this.activeResultTab === 'chart' && this.chartData.length > 0) {
					console.log('当前在面积图标签页，立即渲染图表')
					this.$nextTick(() => {
						this.renderAreaChart()
					})
				}
			} else {
				// 按资产大类模式时，获取图表数据
				this.getChartData()
			}
		},

		// 渲染面积图
		renderAreaChart() {
			if (!this.chartData.length) {
				console.log('图表数据为空，无法渲染面积图')
				return
			}

			console.log('开始渲染面积图，数据:', this.chartData)
			console.log('当前选择模式:', this.selectionMode)

			this.$nextTick(() => {
				// 获取图表容器
				const chartDom = document.getElementById('areaChart')
				if (!chartDom) {
					console.log('找不到图表容器')
					return
				}

				// 如果已经存在图表实例，先销毁
				if (this.$areaChart) {
					this.$areaChart.dispose()
				}

				// 初始化图表
				const myChart = echarts.init(chartDom)

				// 准备数据
				const years = this.chartData.map(item => item.year).filter(year => year !== null)
				const series = []

				if (this.selectionMode === 'city') {
					// 按地市模式：为每个地市创建一条数据线
					console.log('按地市模式渲染图表，地市列:', this.cityColumns)
					this.cityColumns.forEach(city => {
						const data = this.chartData.map(item => item[city.key] || 0)
						console.log(`地市 ${city.label} 的数据:`, data)
						series.push({
							name: city.label,
							type: 'line',
							areaStyle: {
								opacity: 0.6
							},
							lineStyle: {
								width: 2
							},
							data: data,
							itemStyle: {
								color: city.color
							}
						})
					})
				} else {
					// 按资产大类模式：为每个电压等级创建一条数据线
					const voltageColumns = this.columnConfigs[Number(this.assetCategory)] || []
					voltageColumns.forEach((voltage, index) => {
						const data = this.chartData.map(item => item[voltage.key] || 0)
						series.push({
							name: voltage.label,
							type: 'line',
							areaStyle: {
								opacity: 0.6
							},
							lineStyle: {
								width: 2
							},
							data: data,
							itemStyle: {
								color: this.getVoltageColor(index)
							}
						})
					})
				}

				// 根据选择模式设置标题
				const titleText = this.selectionMode === 'city'
					? '各地市资产原值统计'
					: `各类型资产原值`

				// 根据选择模式设置图例数据
				const legendData = this.selectionMode === 'city'
					? this.cityColumns.map(city => city.label)
					: (this.columnConfigs[Number(this.assetCategory)] || []).map(voltage => voltage.label)

				const option = {
					title: {
						text: titleText,
						left: 'center',
						top: 10,
						textStyle: {
							fontSize: 16,
							fontWeight: 'bold',
							color: '#333'
						}
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'cross',
							label: {
								backgroundColor: '#6a7985'
							}
						}
					},
					legend: {
						data: legendData,
						top: 40,
						left: 'center'
					},
					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						boundaryGap: false,
						data: years,
						axisLabel: {
							color: '#333'
						}
					},
					yAxis: {
						type: 'value',
						min: 0,
						max: function (value) {
							// 计算所有数据中的最大值
							let maxValue = 0
							series.forEach(s => {
								s.data.forEach(val => {
									if (val > maxValue) {
										maxValue = val
									}
								})
							})
							return maxValue
						},
						axisLabel: {
							color: '#333'
						}
					},
					series: series
				}

				// 设置图表配置并渲染
				myChart.setOption(option)

				// 保存图表实例，用于后续操作
				this.$areaChart = myChart
			})
		},

		// 处理地图数据
		processMapData(data) {
			if (!data || data.length === 0) {
				this.mapData = []
				return
			}

			// 如果是按地市模式，处理地图数据
			if (this.selectionMode === 'city') {
				// 获取接口返回的数据（固定只返回一条数据，year为null）
				const mapDataItem = data.find(item => item.year === null) || data[0]

				if (mapDataItem) {
					// 使用 areaData 中的地市信息，与接口返回的数据进行匹配
					this.mapData = areaData.map(area => {
						// 从 cityColumns 中找到对应的数据
						const cityColumn = this.cityColumns.find(city =>
							city.label.includes(area.briefName)
						)

						const value = cityColumn ? (mapDataItem[cityColumn.key] || 0) : 0

						return {
							name: area.briefName + '市', // 使用 areaData 中的 briefName 加上"市"，与 GeoJSON 中的名称匹配
							value: value
						}
					})


				}
			} else {
				// 按资产大类模式时，地图显示为空
				this.mapData = []
			}

			// 如果切换到地图标签页，立即渲染地图
			if (this.activeResultTab === 'map' && this.mapData.length > 0) {
				this.$nextTick(() => {
					this.renderFujianMap()
				})
			}
		},

		// 渲染福建省地图
		renderFujianMap() {
			if (!this.mapData.length) return

			this.$nextTick(() => {
				// 获取地图容器
				const mapDom = document.getElementById('fujianMap')
				if (!mapDom) return

				// 如果已经存在地图实例，先销毁
				if (this.$map) {
					this.$map.dispose()
				}

				// 注册福建省地图数据
				echarts.registerMap('fujian', fujianMapData)

				// 初始化地图
				const myMap = echarts.init(mapDom)

				const option = {
					title: {
						text: '各地市资产原值',
						left: 'center',
						top: 10,
						textStyle: {
							fontSize: 16,
							fontWeight: 'bold',
							color: '#333'
						}
					},

					visualMap: {
						min: 0,
						max: Math.max(...this.mapData.map(item => item.value), 1),
						left: 'left',
						top: 'bottom',
						text: ['高', '低'],
						calculable: true,
						inRange: {
							color: ['#e0f3f8', '#55b1bb', '#0d47a1']
						}
					},
					geo: [
						{
							map: 'fujian',
							roam: false,
							aspectScale: 1,
							label: { show: false },
							itemStyle: {
								opacity: 1,
								borderWidth: 2,
								borderColor: '#fff',
							},
							zlevel: 1
						},
						{
							map: 'fujian',
							aspectScale: 1,
							roam: false,
							label: { show: false },
							silent: true,
							itemStyle: {
								opacity: 1,
								shadowColor: '#A0C3BC',
								shadowBlur: 2,
								shadowOffsetX: 5,
								shadowOffsetY: 6
							},
							zlevel: 2
						}
					],
					series: [
						{
							type: 'map',
							map: 'fujian',
							layoutSize: '100%',
							aspectScale: 1,
							selectedMode: 'single',
							roam: false,
							label: {
								show: true,
								fontWeight: 'bold',
								color: '#fff',
								fontSize: 12,
								textShadowColor: 'rgba(0,0,0,0.41)',
								textShadowBlur: 4,
								textShadowOffsetX: 0,
								textShadowOffsetY: 2,
								formatter: function (params) {
									// 显示地市名称和数值
									return params.name + '\n' + params.value
								}
							},
							itemStyle: {
								opacity: 0.8,
								borderColor: "#fff",
								borderWidth: 2,
								shadowColor: 'rgb(33, 229, 159, 0.3)',
								shadowBlur: 25
							},
							select: {
								label: { show: true, color: '#eee' },
								itemStyle: { areaColor: '#008C00' }
							},
							emphasis: {
								label: { show: true, color: '#eee' },
								itemStyle: { areaColor: '#008C00' }
							},
							data: this.mapData,
							zlevel: 3
						}
					]
				};

				// 设置地图配置并渲染
				myMap.setOption(option)

				// 保存地图实例，用于后续操作
				this.$map = myMap
			})
		},



		// 导出结果表
		async exportResults() {
			// 验证参数
			if (this.selectionMode === 'city' && !this.city) {
				this.$message.warning('请先选择地市并执行分析')
				return
			}

			if (this.selectionMode === 'category' && !this.assetCategory) {
				this.$message.warning('请先选择资产大类并执行分析')
				return
			}

			if (this.tableData.length === 0) {
				this.$message.warning('暂无数据可导出，请先执行分析')
				return
			}

			try {
				// 构建导出参数
				const params = {
					yearStart: parseInt(this.startYear),
					yearEnd: parseInt(this.endYear)
				}

				let response
				let filename

				// 根据选择模式调用不同的导出接口
				if (this.selectionMode === 'city') {
					// 按地市模式：调用 dataAnalysisExportCity 接口
					// 导出时根据当前激活的标签页决定city参数
					if (this.activeResultTab === 'table') {
						params.city = 1  // 1-列表
					} else if (this.activeResultTab === 'map') {
						params.city = 2  // 2-地图
					} else {
						params.city = 1  // 默认列表模式
					}

					response = await dataAnalysisExportCity(params)
					filename = `地市资产分析结果_${this.startYear}-${this.endYear}.xlsx`
				} else {
					// 按资产大类模式：调用 dataAnalysisExport 接口
					params.astCategory = this.getAssetCategoryCode(this.assetCategory)
					response = await dataAnalysisExport(params)
					filename = `资产分析结果_${this.getAssetCategoryName()}_${this.startYear}-${this.endYear}.xlsx`
				}

				// 验证响应数据
				if (response && this.isValidBlob(response)) {
					this.downloadExcelFile(response, filename)
					this.$message.success('导出成功')
				} else {
					// 尝试解析错误信息
					if (response && typeof response === 'object') {
						this.$message.error('导出失败：' + (response.msg || '未知错误'))
					} else {
						this.$message.error('导出失败，未获取到有效的文件数据')
					}
				}
			} catch (error) {
				console.error('导出失败:', error)
				this.$message.error('导出失败，请稍后重试')
			}
		},

		// 验证是否为有效的Blob数据
		isValidBlob(data) {
			// 检查是否为Blob对象
			if (data instanceof Blob) {
				return true
			}

			// 检查是否为ArrayBuffer
			if (data instanceof ArrayBuffer) {
				return true
			}

			// 检查是否为TypedArray
			if (ArrayBuffer.isView && ArrayBuffer.isView(data)) {
				return true
			}

			return false
		},

		// 获取资产大类编码
		getAssetCategoryCode(categoryName) {
			const categoryMap = {
				'变电设备': 1,
				'配电线路及设备': 2,
				'输电线路': 3
			}
			return categoryMap[categoryName] || 1
		},

		// 获取资产大类名称
		getAssetCategoryName() {
			const categoryMap = {
				'1': '变电设备',
				'2': '配电线路及设备',
				'3': '输电线路'
			}
			return categoryMap[this.assetCategory] || '变电设备'
		},

		// 获取电压等级颜色
		getVoltageColor(index) {
			const colors = [
				'#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
				'#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#ff9f7f',
				'#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57'
			]
			return colors[index % colors.length]
		},

		// 下载Excel文件
		downloadExcelFile(blobData, filename) {
			try {


				// 确保传入的是有效的数据
				if (!this.isValidBlob(blobData)) {
					console.error('传入的数据不是有效的Blob对象:', blobData)
					this.$message.error('文件数据格式错误')
					return
				}

				// 如果是ArrayBuffer，转换为Blob
				let blob
				if (blobData instanceof ArrayBuffer) {
					blob = new Blob([blobData], {
						type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
					})
				} else {
					blob = blobData
				}

				// 创建下载链接
				const url = window.URL.createObjectURL(blob)
				const link = document.createElement('a')
				link.href = url
				link.download = filename

				// 设置链接样式（隐藏）
				link.style.display = 'none'

				// 添加到DOM并触发下载
				document.body.appendChild(link)
				link.click()

				// 清理
				document.body.removeChild(link)
				window.URL.revokeObjectURL(url)


			} catch (error) {
				console.error('文件下载失败:', error)
				this.$message.error('文件下载失败，请稍后重试')
			}
		}
	},

	mounted() {
		// 默认选中存量标签页
		this.activeTab = 'stock'
		// 默认选中实物资产墙
		this.activeNavItem = 'physical'
		// 确保有默认的资产大类
		if (!this.assetCategory) {
			this.assetCategory = '1'
		}

		// 添加窗口大小变化监听器
		this.handleResize = () => {
			if (this.$map) {
				this.$map.resize()
			}
			if (this.$areaChart) {
				this.$areaChart.resize()
			}
		}
		window.addEventListener('resize', this.handleResize)
	},

	beforeDestroy() {
		// 清理地图实例
		if (this.$map) {
			this.$map.dispose()
			this.$map = null
		}
		// 清理图表实例
		if (this.$areaChart) {
			this.$areaChart.dispose()
			this.$areaChart = null
		}
		// 移除窗口大小变化监听器
		window.removeEventListener('resize', this.handleResize)
	}
}
</script>

<style scoped>
.asset-risk-analysis {
	display: flex;
	height: 100vh;
	background-color: #f5f5f5;
}

.left-nav-panel {
	width: 250px;
	background-color: #fff;
	border-right: 1px solid #e4e7ed;
	overflow: hidden;
}

.nav-tabs {
	height: 100%;
}

.nav-tabs :deep(.el-tabs__header) {
	margin: 0;
	padding: 0 20px;
	background: #fafafa;
	border-bottom: 1px solid #e4e7ed;
}

.nav-tabs :deep(.el-tabs__content) {
	height: calc(100% - 40px);
	overflow-y: auto;
	padding: 20px;
}

.nav-tabs :deep(.el-tabs__nav-wrap) {
	display: flex;
}

.nav-tabs :deep(.el-tabs__nav) {
	width: 100%;
	display: flex;
}

.nav-tabs :deep(.el-tabs__item) {
	height: 40px;
	line-height: 40px;
	font-size: 16px;
	font-weight: bold;
	color: #606266;
	flex: 1;
	text-align: center;
}

.nav-tabs :deep(.el-tabs__item.is-active) {
	color: #409eff;
}

.nav-content {
	padding: 10px 0;
}

.nav-item {
	padding: 15px 20px;
	cursor: pointer;
	border-left: 3px solid transparent;
	margin-bottom: 5px;
	transition: all 0.3s;
}

.nav-item:hover {
	background-color: #f5f7fa;
}

.nav-item.active {
	background-color: #e8f5e8;
	border-left-color: #67c23a;
}

.nav-title {
	font-size: 16px;
	font-weight: 500;
	color: #333;
}

.main-content {
	flex: 1;
	padding: 0 20px;
	overflow-y: auto;
}

.model-script-section,
.parameter-section,
.result-section {
	background-color: #fff;
	border-radius: 8px;
	margin-bottom: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h3 {
	margin: 0 0 20px 0;
	font-size: 18px;
	font-weight: 600;
	color: #333;
}

.code-editor {
	background-color: #1e1e1e;
	border-radius: 6px;
	overflow: auto;
	height: 500px;
}

.code-content {
	margin: 0;
	padding: 20px;
	color: #d4d4d4;
	font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
	font-size: 14px;
	line-height: 1.5;
	white-space: pre-wrap;
	overflow-x: auto;
}

.parameter-form {
	display: flex;
	flex-direction: column;
	gap: 20px;
	padding: 20px;
}

.selection-mode {
	display: flex;
	align-items: center;
	gap: 20px;
	padding: 15px 0;
	border-bottom: 1px solid #ebeef5;
}

.mode-label {
	font-size: 14px;
	font-weight: 500;
	color: #333;
}

.form-row {
	display: flex;
	gap: 30px;
	align-items: flex-end;
}

.form-row {
	display: flex;
	gap: 30px;
}

.form-item {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.form-item label {
	font-size: 14px;
	font-weight: 500;
	color: #333;
}

select {
	padding: 8px 12px;
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	font-size: 14px;
	min-width: 120px;
}

.year-range {
	display: flex;
	align-items: center;
	gap: 8px;
}

.separator {
	color: #666;
}

.form-actions {
	display: flex;
	gap: 12px;
}

.btn {
	padding: 10px 20px;
	border: none;
	border-radius: 4px;
	font-size: 14px;
	cursor: pointer;
	transition: all 0.3s;
}

.btn-reset {
	background-color: #f5f5f5;
	color: #666;
	border: 1px solid #dcdfe6;
}

.btn-execute {
	background-color: #67c23a;
	color: white;
}

.btn-execute:hover {
	background-color: #5daf34;
}

.result-tabs {
	padding: 0 10px;
	margin-bottom: 20px;
}

.result-tabs :deep(.el-tabs__header) {
	margin-bottom: 20px;
}

.result-tabs :deep(.el-tabs__nav-wrap) {
	border-bottom: 1px solid #e4e7ed;
}

.result-tabs :deep(.el-tabs__item) {
	font-size: 14px;
	font-weight: 500;
	color: #606266;
	padding: 0 20px;
	height: 40px;
	line-height: 40px;
}

.result-tabs :deep(.el-tabs__item.is-active) {
	color: #409eff;
}

.result-tabs :deep(.el-tabs__active-bar) {
	background-color: #409eff;
}

.chart-container,
.map-container {
	min-height: 400px;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #fafafa;
	border-radius: 6px;
	border: 1px dashed #d9d9d9;
}

.map-content {
	width: 100%;
	height: 400px;
	min-height: 400px;
}

.chart-content {
	width: 100%;
	height: 400px;
	min-height: 400px;
}

.chart-placeholder,
.map-placeholder {
	text-align: center;
	color: #999;
}

.chart-placeholder p,
.map-placeholder p {
	margin: 0;
	font-size: 16px;
}

.result-table {
	margin-bottom: 20px;
	overflow-x: auto;
}

table {
	width: 100%;
	border-collapse: collapse;
	font-size: 14px;
}

th,
td {
	padding: 12px 8px;
	text-align: left;
	border-bottom: 1px solid #ebeef5;
}

th {
	background-color: #fafafa;
	font-weight: 600;
	color: #333;
}

td {
	color: #666;
}

.result-actions {
	display: flex;
	justify-content: flex-end;
	gap: 12px;
	padding: 0 20px 20px 20px;
}

.btn-add-dataset,
.btn-export {
	background-color: #67c23a;
	color: white;
}

.btn-add-dataset:hover,
.btn-export:hover {
	background-color: #5daf34;
}

.no-data {
	text-align: center;
	padding: 40px 20px;
	color: #999;
}

.no-data p {
	margin: 0;
	font-size: 16px;
}

.card-title {
	font-size: 16px;
	font-weight: bold;
	color: #333;
	padding: 16px 20px;
	border-bottom: 1px solid #e6e6e6;
	background: #fafafa;
}
</style>
